package com.superhelper.superhelper_web.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.superhelper.common.domain.AuserShop;
import com.superhelper.common.domain.PushMsgType;
import com.superhelper.common.domain.TakeOutOrderStatus;
import com.superhelper.common.utils.JsonHelper;
import com.superhelper.superhelper_web.common.CommonHelper;
import com.superhelper.superhelper_web.controller.base.AbstractController;
import com.superhelper.superhelper_web.domain.Admin;
import com.superhelper.superhelper_web.domain.AuserShopAudio;
import com.superhelper.superhelper_web.domain.Order;
import com.superhelper.superhelper_web.domain.PageModel;
import com.superhelper.superhelper_web.domain.Resp;
import com.superhelper.superhelper_web.service.ElemeService;
import com.superhelper.superhelper_web.service.MtService;
import com.superhelper.superhelper_web.service.OrderService;
import com.superhelper.superhelper_web.service.ShopService;
import com.superhelper.superhelper_web.service.deliver.IDeliverService;

import eleme.openapi.sdk.api.exception.ServiceException;

@Controller
@RequestMapping("admin/order")
public class OrderController extends AbstractController {

	@Autowired
	private ShopService shopService;
	@Autowired
	private OrderService orderService;

	@Autowired
	private ElemeService elemeService;

	@Autowired
	private MtService mtService;

	@Autowired
	private IDeliverService dadaService;

	/**
	 * 查看
	 * 
	 * @return
	 * @throws ServiceException
	 */
	@RequestMapping("list")
	public String list(ModelMap model, HttpServletRequest request,
			PageModel pageModel) throws ServiceException {
		String orderStatus = request.getParameter("status");
		String type = request.getParameter("type");
		String book = request.getParameter("book");
		String array[] = orderStatus.split(",");
		List<String> listStatus = new ArrayList<String>();
		for (String s : array) {
			s = s.replaceAll("'", "");
			listStatus.add("'" + s + "'");
		}
		pageModel.getQueryMap()
				.put("status", StringUtils.join(listStatus, ","));
		Calendar c = Calendar.getInstance();
		c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) - 1);
		Date date_sub = CommonHelper.getDateFormat("yyyy-MM-dd", c.getTime());
		if (orderStatus.contains("refunding")) {
			c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) - 3);
			date_sub = CommonHelper.getDateFormat("yyyy-MM-dd", c.getTime());
		}
		pageModel.getQueryMap().put("type", type);
		pageModel.getQueryMap().put("book", book);
		Admin admin = CommonHelper.getSessionUser();
		List<AuserShop> shops = shopService.getAuserShopsByAuserId(admin
				.getId());
		List<String> shopIds = new ArrayList<String>();
		shopIds.add("0");
		if (pageModel.getQueryMap() != null
				&& StringUtils.isNotBlank(pageModel.getQueryMap().get("type"))
				&& !pageModel.getQueryMap().get("type").equals("all")) {
			for (AuserShop s : shops) {
				if (s.getShop_type().contains(
						pageModel.getQueryMap().get("type"))) {
					shopIds.add(s.getShopId());
				}
			}
		} else {
			for (AuserShop s : shops) {
				shopIds.add(s.getShopId());
			}
		}
		pageModel.getQueryMap().put("shopIds", StringUtils.join(shopIds, ","));
		List<Order> list = orderService.getTakeOutOrder(pageModel, date_sub);
		model.put("list", list);
		return "admin/order/list";
	}

	/**
	 * 订单处理
	 * 
	 * @return
	 * @throws ServiceException
	 */
	@RequestMapping("handle")
	@ResponseBody
	public Resp handle(@RequestParam Long orderId, String dataType)
			throws Exception {

		Order order = orderService.getOrderByOrderId(orderId);
		if (order == null) {
			return fail("订单不存在");
		}
		boolean res = false;
		switch (dataType) {
		case "confirm": // 确认订单
			if (order.getStatus().equals(
					TakeOutOrderStatus.UNPROCESSED.getValue())) {
				if (AuserShop.SHOP_ELEME.equals(order.getType())) {
					res = elemeService.confirmOrder(order.getShopId(),
							order.getPlfOrderId());
				} else {
					res = mtService.confirmOrder(order.getShopId(),
							order.getPlfOrderId());
				}
			}
			break;

		case "canel": // 取消订单
			if (order.getStatus().equals(
					TakeOutOrderStatus.UNPROCESSED.getValue())
					|| order.getStatus().equals(
							TakeOutOrderStatus.VALID.getValue())) {
				res = orderService.canelOrder(order);
			}
			break;

		case "send": // 发送物流
			res = dadaService.addTask(orderId);
			break;

		case "print": // 打印

			break;

		case "agree": // 同意退款申请
			if (order.getStatus().equals(
					TakeOutOrderStatus.REFUNDING.getValue())
					|| order.getStatus().equals(
							TakeOutOrderStatus.APPLY_CANCEL.getValue())) {
				res = orderService.agreeOrder(order);
			}
			break;
		case "disagree": // 退款申请取消
			if (order.getStatus().equals(
					TakeOutOrderStatus.REFUNDING.getValue())
					|| order.getStatus().equals(
							TakeOutOrderStatus.APPLY_CANCEL.getValue())) {
				if (AuserShop.SHOP_ELEME.equals(order.getType())) {
					res = elemeService.disagreeRefund(order.getShopId(),
							order.getPlfOrderId());
				} else {
					res = mtService.disagreeRefund(order.getShopId(),
							order.getPlfOrderId());
				}
			}
			break;
		default:
			break;
		}
		log.info("handle：{}-{}-{}", orderId, dataType, res);
		return res ? success("操作成功") : fail("操作失败");
	}

	/**
	 * 获取打单信息（页面打单）
	 * 
	 * @return
	 * @throws ServiceException
	 */
	@RequestMapping("print")
	@ResponseBody
	public Resp print(@RequestParam Long orderId) throws ServiceException {
		Order order = orderService.getOrderByOrderId(orderId);
		log.info("页面打印print：{}", JsonHelper.toJson(order));
		return order != null ? success(order) : fail("");
	}

	/**
	 * 自动接单
	 * 
	 * @return
	 * @throws ServiceException
	 */
	@RequestMapping("receiver")
	@ResponseBody
	public Resp receiver(@RequestParam Long orderId) throws Exception {
		Order order = orderService.getOrderByOrderId(orderId);
		boolean res = false;
		if (AuserShop.SHOP_ELEME.equals(order.getType())) {
			res = elemeService.confirmOrder(order.getShopId(),
					order.getPlfOrderId());
		} else {
			res = mtService.confirmOrder(order.getShopId(),
					order.getPlfOrderId());
		}
		log.info("receiver:{}-{}", orderId, res);
		return res ? success("操作成功") : fail("操作失败");
	}

	/**
	 * 队列信息
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("mq")
	@ResponseBody
	public Resp redisMq() {
		Admin user = CommonHelper.getSessionUser();
		List<AuserShop> shops = shopService
				.getAuserShopsByAuserId(user.getId());
		String msg = null;
		for (AuserShop s : shops) {
			if (s.getOrderAuto() == 1) {
				String type = s.getShop_type();
				String shopId = s.getShopId();
				String key = String.format(
						com.superhelper.common.Consts.Redis.SUB_ORDER, type,
						shopId);
				msg = redisService.lpop(key);
				if (StringUtils.isNotBlank(msg)) {
					break;
				}
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(msg)) {
			log.info("mq-msg:{}", msg);
			map = JsonHelper.fromJson(msg, Map.class);
			Long orderId = Long.parseLong(map.get("orderId") + "");
			Order order = orderService.getOrderByOrderId(orderId);
			if (order != null) {
				boolean flag = false;
				if (order.getStatus().equals(
						TakeOutOrderStatus.APPLY_CANCEL.getValue())
						|| order.getStatus().equals(
								TakeOutOrderStatus.REFUNDING.getValue())) {
					flag = true;
				} else {
					if (order.getCreateAt().getTime() > user.getLoginAt()
							.getTime()) {
						flag = true;
					}
				}
				if (flag) {
					log.info("mq-msg-right:{}", map.toString());
					String type = (String) map.get("type");
					Boolean book = (Boolean) map.get("book");
					map.put("orderId", orderId);
					map.put("type", type);
					map.put("book", book);
					if (PushMsgType.ORDER_APPLY_CANCEL.getValue().equals(
							map.get("type").toString())) {// 用户申请取消
						map.put("type", PushMsgType.ORDER_CANCELED.getValue());
					} else if (PushMsgType.DELIVER_EXCEPTION.getValue().equals(
							map.get("type").toString())
							|| PushMsgType.DELIVER_MONEY_EXCEPTION.getValue()
									.equals(map.get("type").toString())) {
						map.put("type",
								PushMsgType.DELIVER_EXCEPTION.getValue());

					}
					List<AuserShopAudio> audios = shopService
							.getAuserAudioByAuserId(user.getId());
					for (AuserShopAudio a : audios) {
						if (a.getType().equals(map.get("type").toString())) {
							map.put("count", a.getCount());
							map.put("src", a.getSrc());
						}
					}
					return success(map);
				}
			}
		}
		map.clear();
		return success(map);
	}

	/**
	 * 自动打单
	 * 
	 * @return
	 * @throws ServiceException
	 */
	@RequestMapping("queryOrder")
	@ResponseBody
	public Resp queryOrder() {
		Admin user = CommonHelper.getSessionUser();
		List<AuserShop> shops = shopService
				.getAuserShopsByAuserId(user.getId());
		List<String> shopIds = new ArrayList<String>();
		for (AuserShop s : shops) {
			if (s.getOrderAuto() == 1) {
				shopIds.add(s.getShopId());
			}
		}
		List<Order> orders = orderService.querOrderToPrint(shopIds,
				user.getLoginAt());
		log.info("queryOrder:{}", JsonHelper.toJson(orders));
		return success(orders);
	}

	/**
	 * 更新打单状态
	 * 
	 * @return
	 * @throws ServiceException
	 */
	@RequestMapping("updateProcess")
	@ResponseBody
	public Resp updateProcess(@RequestParam String ids,
			@RequestParam Integer state) {
		int res = orderService.updateProcess(ids, state);
		log.info("updateProcess-{}-{}-{}", ids, state, res);
		return res > 0 ? success("更新成功") : fail("更新失败");
	}
}
